'use strict';

import React, {Component} from "react";
import {
    View,
    Image,
    Text,
    TouchableOpacity,
    StyleSheet,
    ListView,
    ActivityIndicator
} from "react-native";
import ViewPager from "react-native-viewpager";
import CountryHallListView from "../Components/CountryHallListView";
import CountryHomePage from "./CountryHomePage";
import ImageViewer from "./ImageViewer";
import Global from "../Commom/GlobalConst";
import * as types from "../Commom/ActionConst";
import HeadlineList from "../Pages/HeadlineList";
import HeadlineDetails from "../Pages/HeadlineDetails";
import RuralLibraryAPIService from "../Commom/RuralLibraryAPIService";
import Toast from "../Utils/toast";
let {width} = Global.Const.size;
const styles = StyleSheet.create({
    titleBox: {
        height: 65,
        paddingTop: 10,
        alignItems: 'center',
        flexDirection: 'row',
    },
    titleLeftBox: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 35,
        width: 60,
    },
    leftText: {
        fontSize: 16,
        color: '#38D68B',
        marginLeft: 10,
        textAlign: 'center',
        textAlignVertical: 'center',
    },
    icon15: {
        width: 15,
        height: 15,
        marginLeft: 5,
    },
    titleText: {
        fontSize: 20,
        color: Global.FontColor.DimGray,
        textAlign: 'center',
        flex: 1,
        marginRight: 60,
    }
});

export default class RuralLibraryPage extends Component {

    constructor(props) {
        super(props);
        var RuralData = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        var dsCity = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        var dsArea = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        var dsTown = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            flag: false,
            RuralDataSource: RuralData,
            ruraLibraryImages: [],
            RuralLibrary: [],
            isCity: false,
            isArea: false,
            AllData: [],
            dataSourceCity: dsCity,
            allCity: [],
            dataSourceArea: dsArea,
            allArea: [],
            dataSourceTown: dsTown,
            allTown: [],
            cursorSelectCity: 0,
            cursorSelectArea: 0,
            city: '珠海市',
            area: '金湾区',
            town: '斗门镇',
            showNumber: -1,
            record_count: 1,
            page: 1,
            isRefreshing: false,
        }
        this.showView = this.showView.bind(this);
        this.initCityData = this.initCityData.bind(this);
        this.chooseTown = this.chooseTown.bind(this);
        this.getTown = this.getTown.bind(this);
    }

    componentDidMount() {
        this.setState({
            isRefreshing: true,
        });

        this.getTown();
        const {dispatch} = this.props;
        RuralLibraryAPIService.citiesList().then((ret)=> {
            this.initCityData(ret.citys);
            dispatch({type: types.kCityListReceived, result: ret});
        }).catch((err)=> {
            dispatch({type: types.kCityListReceived, result: null});
        });
        RuralLibraryAPIService.ruraLibraryImagesList().then((ret)=> {
            this.setState({
                ruraLibraryImages: ret,
            });
        }).catch((err)=> {

        });
    }

    getTown() {
        RuralLibraryAPIService.get_town(Global.Const.longitude, Global.Const.latitude).then((ret)=> {
            this.setState({
                city: ret.city.name,
                area: ret.area.name,
                town: '全部',
            });
            this.chooseTown('全部');
        }).catch((err)=> {

        });
    }

    onRefresh() {
        console.log('town==', this.state.town);
        this.setState({
            isRefreshing: true,
        });
        RuralLibraryAPIService.ruralLibraryList(Global.Const.longitude, Global.Const.latitude, this.state.town, 1).then((ret)=> {
            this.setState({
                isRefreshing: false,
                RuralLibrary: ret.result,
                record_count: ret.record_count,
                page: Number(ret.page),
                RuralDataSource: this.state.RuralDataSource.cloneWithRows(ret.result),
            });
            Toast.show('刷新成功');
        }).catch((err)=> {
            this.setState({
                isRefreshing: false,
                RuralLibrary: [],
                RuralDataSource: this.state.RuralDataSource.cloneWithRows([]),
            });
        });
    }

    chooseTown(town) {
        console.log('town', town);
        this.setState({
            isRefreshing: true,
        });
        RuralLibraryAPIService.ruralLibraryList(Global.Const.longitude, Global.Const.latitude, town, 1).then((ret)=> {
            console.log('66666',ret)
            this.setState({
                flag: true,
                isRefreshing: false,
                RuralLibrary: ret.result,
                record_count: ret.record_count,
                page: Number(ret.page),
                RuralDataSource: this.state.RuralDataSource.cloneWithRows(ret.result),
            });
            Toast.show('刷新成功');
        }).catch((err)=> {
            this.setState({
                flag: true,
                isRefreshing: false,
                RuralLibrary: [],
                RuralDataSource: this.state.RuralDataSource.cloneWithRows([]),
            });
        });
    }

    //加载更多数据
    loadMoreData() {
        if (this.state.page < this.state.record_count) {
            this.setState({
                isRefreshing: true,
            });
            RuralLibraryAPIService.ruralLibraryList(Global.Const.longitude, Global.Const.latitude, this.state.town, this.state.page).then((ret)=> {
                let wanjian = [];
                wanjian = this.state.RuralLibrary;
                for (var i = 0; i < ret.result.length; i++) {
                    wanjian.push(ret.result[i])
                }
                this.setState({
                    isRefreshing: false,
                    RuralLibrary: wanjian,
                    record_count: ret.record_count,
                    page: Number(ret.page),
                    RuralDataSource: this.state.RuralDataSource.cloneWithRows(wanjian),
                });
                Toast.show('加载成功');
            }).catch((err)=> {

            });
        } else {
            if (this.state.page != 1) {
                Toast.show('木有更多数据');
            }
        }

    }

    initCityData(data) {
        var allds = data;
        var allcategory = [];

        for (let i = 0; i < allds.length; i++) {
            if (i == 0) {
                allcategory.push({name: allds[i].city, isCity: true});
            }
            else {
                allcategory.push({name: allds[i].city, isCity: false});
            }
        }
        var allAreaTown = [];
        allAreaTown.push({name: allds[0].areas, isArea: true});
        for (let i = 0; i < allds[0].areas.length; i++) {
            if (i == 0) {
                allAreaTown.push({name: allds[0].areas, isArea: true});
            } else {
                allAreaTown.push({name: allds[0].areas, isArea: false});
            }
        }
        const {dispatch} = this.props;
        dispatch({type: types.CurrentCity, city: allcategory[0].name});
        var towns=[];
        towns.push({town:'全部',id:0});
        towns=towns.concat(allAreaTown[0].name[0].towns);
        this.setState({
            AllData: data,
            // city: allcategory[0].name,
            // area: allAreaTown[0].name[0].area,
            // town: allAreaTown[0].name[0].towns[0].town,
            allCity: allcategory,
            dataSourceCity: this.state.dataSourceCity.cloneWithRows(allcategory),
            allArea: allAreaTown,
            dataSourceArea: this.state.dataSourceArea.cloneWithRows(allAreaTown),
            allTown: towns,
            dataSourceTown: this.state.dataSourceTown.cloneWithRows(towns),
        });

    }

    selectCity(rowID) {
        let newArray = this.state.allCity.concat();
        newArray[this.state.cursorSelectCity] = {
            ...this.state.allCity[this.state.cursorSelectCity],
            isCity: false,
        }
        newArray[rowID] = {
            ...this.state.allCity[rowID],
            isCity: true,
        }

        var allds = this.state.AllData;
        var allAreaTown = [];
        for (let i = 0; i < allds[rowID].areas.length; i++) {
            if (i == 0) {
                allAreaTown.push({name: allds[rowID].areas, isArea: true});
            } else {
                allAreaTown.push({name: allds[rowID].areas, isArea: false});
            }
        }
        const {dispatch} = this.props;
        dispatch({type: types.CurrentCity, area: this.state.allCity[rowID].name});

        this.setState({
            city: this.state.allCity[rowID].name,
            area: allAreaTown[0].name[0].area,
            town: allAreaTown[0].name[0].towns[0].town,
            cursorSelectCity: rowID,
            allCity: newArray,
            cursorSelectArea: 0,
            dataSourceCity: this.state.dataSourceCity.cloneWithRows(newArray),
            allArea: allAreaTown,
            dataSourceArea: this.state.dataSourceArea.cloneWithRows(allAreaTown),
            allTown: allAreaTown[0].name[0].towns,
            dataSourceTown: this.state.dataSourceTown.cloneWithRows(allAreaTown[0].name[0].towns),
            showNumber: -1,
        });
        this.chooseTown(allAreaTown[0].name[0].towns[0].town);
    }

    selectArea(rowID) {
        let newArrayArea = this.state.allArea.concat();
        newArrayArea[this.state.cursorSelectArea] = {
            ...this.state.allArea[this.state.cursorSelectArea],
            isArea: false,
        }
        newArrayArea[rowID] = {
            ...this.state.allArea[rowID],
            isArea: true,
        }
        var allds = this.state.allArea;
        const {dispatch} = this.props;
        dispatch({type: types.CurrentCity, area: this.state.allArea[rowID].name[rowID].area});
        this.setState({
            area: this.state.allArea[rowID].name[rowID].area,
            town: this.state.allArea[rowID].name[rowID].towns[0].town,

            cursorSelectArea: rowID,
            allArea: newArrayArea,
            dataSourceArea: this.state.dataSourceArea.cloneWithRows(newArrayArea),

            allTown: allds[0].name[rowID].towns,
            dataSourceTown: this.state.dataSourceTown.cloneWithRows(allds[0].name[rowID].towns),
            showNumber: -1,
        });
        this.chooseTown(this.state.allArea[rowID].name[rowID].towns[0].town);
    }

    selectTown(rowID) {
        console.log('==',rowID);
        console.log('==',this.state.allTown[rowID])
        console.log('==',this.state.allTown)
        const {dispatch} = this.props;
        dispatch({type: types.CurrentCity, town: this.state.allTown[rowID].town});
        this.setState({
            town: this.state.allTown[rowID].town,
            showNumber: -1,
        });
        this.chooseTown(this.state.allTown[rowID].town);
    }

    renderCityRow(rowData, sectionID, rowID) {
        console.log(rowData);
        return (
            <TouchableOpacity
                onPress={()=>this.selectCity(rowID)}>
                <View
                    style={{height:35,justifyContent:'center',alignItems:'center',backgroundColor:'white',borderBottomWidth:1,borderRightWidth:1,borderColor:'#F2F3F5'}}>
                    <Text style={{color:rowData.isCity?'#24CD78':'gray'}}>{rowData.name}</Text>
                </View>
            </TouchableOpacity>
        );
    }

    renderAreaRow(rowData, sectionID, rowID) {
        return (
            <TouchableOpacity
                onPress={()=>this.selectArea(rowID)}>
                <View
                    style={{height:35,justifyContent:'center',alignItems:'center',backgroundColor:'white',borderBottomWidth:1,borderRightWidth:1,borderColor:'#F2F3F5'}}>
                    <Text style={{color:rowData.isArea?'#24CD78':'gray'}}>{rowData.name[rowID].area}</Text>
                </View>
            </TouchableOpacity>
        );
    }

    renderTownRow(rowData, sectionID, rowID) {
        return (
            <TouchableOpacity
                onPress={()=>this.selectTown(rowID)}>
                <View
                    style={{height:35,justifyContent:'center',alignItems:'center',backgroundColor:'white',borderBottomWidth:1,borderRightWidth:1,borderColor:'#F2F3F5'}}>
                    <Text >{rowData.town}</Text>
                </View>
            </TouchableOpacity>
        );
    }

    showView() {
        if (this.state.showNumber != -1) {
            return (
                <View
                    style={{height:Global.Const.size.height-70,backgroundColor:'rgba(0,0,0,0.3)',position:'absolute',left:0,top:70,width:Global.Const.size.width,alignItems:'center'}}>
                    <TouchableOpacity style={{flex:1}}
                                      activeOpacity={0.5}
                                      onPress={()=>this.show(-1)}>
                        <View
                            style={{height:Global.Const.size.height/2-30,width:Global.Const.size.width-90,flexDirection:'row',borderTopWidth:1,borderColor:'#F2F3F5'}}>

                            <View style={{width:(Global.Const.size.width-90)/3}}>
                                {this.state.showNumber == 0 ? <ListView
                                    enableEmptySections={true}
                                    onEndReachedThreshold={50}
                                    dataSource={this.state.dataSourceCity}
                                    renderRow={this.renderCityRow.bind(this)}/> : null}

                            </View>
                            <View style={{width:(Global.Const.size.width-90)/3}}>
                                {this.state.showNumber == 1 ? <ListView
                                    enableEmptySections={true}
                                    onEndReachedThreshold={50}
                                    dataSource={this.state.dataSourceArea}
                                    renderRow={this.renderAreaRow.bind(this)}/> : null}
                            </View>
                            <View style={{width:(Global.Const.size.width-90)/3}}>
                                {this.state.showNumber == 2 ? <ListView
                                    enableEmptySections={true}
                                    onEndReachedThreshold={50}
                                    dataSource={this.state.dataSourceTown}
                                    renderRow={this.renderTownRow.bind(this)}/> : null}
                            </View>
                        </View>
                    </TouchableOpacity>
                </View>
            );
        } else {
            return null;
        }

    }

    show(number) {
        this.setState({
            showNumber: number,
        });
    }


    viewPagerItemClick() {
        var images = [];

        for (let i = 0; i < this.state.ruraLibraryImages.length; i++) {
            images.push(this.state.ruraLibraryImages[i].image_url);
        }
        this.props.navigator.push({
            name: 'ImageViewer',
            component: ImageViewer,
            passProps: {
                source: images,
            }
        })
    }

    _renderPage(page) {
        return (
            <TouchableOpacity onPress={() => this.viewPagerItemClick()}>
                <View style={{ height: 200,
                    width,alignItems:'center'}}>
                    <Image source={{uri:page.image_url}} style={{
                    height: 200,
                    width:width-20,
                }}/>
                </View>
            </TouchableOpacity>
        )
    }

    clonePageData() {
        console.log('ruraLibraryImages',this.state.ruraLibraryImages);
        let dataSource = new ViewPager.DataSource({
            pageHasChanged: (p1, p2) => p1 !== p2
        });
        return dataSource.cloneWithPages(this.state.ruraLibraryImages);
    }

    listItemClick(id) {
        let navigator = this.props.navigator;
        navigator.push({
            name: 'CountryHomePage',
            component: CountryHomePage,
            passProps: {
                ID: id
            }
        });
    }

    headlineClick(id) {
        let navigator = this.props.navigator;
        navigator.push({
            name: 'HeadlineList',
            component: HeadlineList,
            passProps: {
                ID: id
            }
        });
    }

    headlineDetailsClick(data) {
        let navigator = this.props.navigator;
        navigator.push({
            name: 'HeadlineDetails',
            component: HeadlineDetails,
            passProps: {
                data: data
            }
        });
    }

    render() {
        return (
            <View style={{flex: 1}}>
                {this.state.flag ? <View style={{flex: 1}}>
                    <View
                        style={{width:Global.Const.size.width,height:70,backgroundColor:'white',justifyContent:'center',alignItems:'center'}}>
                        <View
                            style={{width:Global.Const.size.width-90,height:32,backgroundColor:'white',borderRadius:4,borderWidth:1,borderColor:'#24CD78',marginTop:24,flexDirection:'row'}}>
                            <TouchableOpacity style={{flex:1}}
                                              // activeOpacity={0.5}
                                              // onPress={()=>this.show(0)}
                            >
                                <View
                                    style={{flex:1,flexDirection:'row',backgroundColor:this.state.showNumber==0?'#24CD78':null,justifyContent:'center',alignItems:'center',borderRightWidth:1,borderColor:'#24CD78'}}>
                                    <Text
                                        style={{color:this.state.showNumber==0?'white':Global.FontColor.DarkGray}}>{this.state.city}</Text>
                                    <Image style={{resizeMode:'contain',width:10,height:12,marginLeft:5}}
                                           source={require('../../Image/up_icon.png')}></Image>

                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity style={{flex:1}}
                                              // activeOpacity={0.5}
                                              // onPress={()=>this.show(1)}
                            >
                                <View
                                    style={{flex:1,flexDirection:'row',backgroundColor:this.state.showNumber==1?'#24CD78':null,justifyContent:'center',alignItems:'center',borderRightWidth:1,borderColor:'#24CD78'}}>
                                    <Text
                                        style={{color:this.state.showNumber==1?'white':Global.FontColor.DarkGray}}>{this.state.area}</Text>
                                    <Image style={{resizeMode:'contain',width:10,height:12,marginLeft:5}}
                                           source={require('../../Image/up_icon.png')}></Image>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity style={{flex:1}}
                                              activeOpacity={0.5}
                                              onPress={()=>this.show(2)}>
                                <View
                                    style={{flex:1,flexDirection:'row',backgroundColor:this.state.showNumber==2?'#24CD78':null,justifyContent:'center',alignItems:'center'}}>
                                    <Text
                                        style={{color:this.state.showNumber==2?'white':Global.FontColor.DarkGray}}>{this.state.town}</Text>
                                    <Image style={{resizeMode:'contain',width:10,height:12,marginLeft:5}}
                                           source={require('../../Image/up_icon.png')}></Image>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <CountryHallListView
                        listItemClick={(id) => this.listItemClick(id)}
                        headlineClick={(id)=>this.headlineClick(id)}
                        headlineDetailsClick={(data)=>this.headlineDetailsClick(data)}
                        isLoading={this.state.isRefreshing}
                        onRefresh={() => this.onRefresh()}
                        loadMoreData={()=>this.loadMoreData()}
                        countryList={this.state.RuralLibrary}
                        enableEmptySections={true}
                        RuralDataSource={this.state.RuralDataSource}
                        renderHead={() => {
                        return (
                            <ViewPager
                                isLoop={true}
                                dataSource={this.clonePageData()}
                                renderPage={(page) => this._renderPage(page)}
                                autoPlay= {true}
                            />
                        )
                    }}
                    />
                    {this.showView()}
                </View> :
                    <View style={{flex:1,backgroundColor:'#F5F5F5'}}><View
                        style={{position: 'absolute',top:0,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                        <View
                            style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                            <ActivityIndicator
                                animating={this.state.animating}
                                style={{ alignItems: 'center',justifyContent: 'center'}}
                                size="large"/>
                            <Text style={{color:'white'}}>加载中...</Text>
                        </View>
                    </View></View>
                }
            </View>
        )
    }
}